﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using WordServices.HttpService;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238

namespace WordsOfLove.ForumPages
{
	/// <summary>
	/// An empty page that can be used on its own or navigated to within a Frame.
	/// </summary>
	public sealed partial class SearchPage : Page
	{
		public SearchPage()
		{
			this.InitializeComponent();
		}

		ObservableCollection<ForumPostInfo> Posts { get; set; }

		protected override void OnNavigatedTo(NavigationEventArgs e)
		{
			base.OnNavigatedTo(e);
			HttpUtils utils = HttpUtilsFactory.Utils;
			SearchPageNavigationArg arg = e.Parameter as SearchPageNavigationArg;
			List<ForumPostInfo> postList;
			string typeStr;
			switch (arg.Mode)
			{
				case SearchPageMode.ByTag:
					postList = utils.SendGetJsonMessage<List<ForumPostInfo>>($"api/ForumPost/GetPostsByTag?tag={arg.SearchContent}");
					typeStr = "单词相关帖子";
					break;
				case SearchPageMode.ByTitle:
					postList = utils.SendGetJsonMessage<List<ForumPostInfo>>($"api/ForumPost/GetPostsByTitle?title={arg.SearchContent}");
					typeStr = "帖子";
					break;
				case SearchPageMode.ByUser:
					postList = utils.SendGetJsonMessage<List<ForumPostInfo>>($"api/ForumPost/GetPostsByUserName?username={arg.SearchContent}");
					typeStr = "用户发帖";
					break;
				case SearchPageMode.ByUserId:
					postList = utils.SendGetJsonMessage<List<ForumPostInfo>>($"api/ForumPost/GetPostsByUserId?id={arg.SearchContent}");
					typeStr = "我的贴子";
					break;
				default:
					throw new InvalidOperationException();
			}
			Posts = new ObservableCollection<ForumPostInfo>(postList);
			if (arg.Mode == SearchPageMode.ByUserId) TitleTxt.Text = "我的贴子";
			else TitleTxt.Text = $"搜索 {typeStr} {arg.SearchContent} 的结果";
			SearchResultListView.ItemsSource = Posts;
		}

		private void SearchResultListView_ItemClick(object sender, ItemClickEventArgs e)
		{
			Frame.Navigate(typeof(PostDetailsPage), e.ClickedItem);
		}
	}

	public enum SearchPageMode
	{
		ByTag, ByTitle, ByUser, ByUserId
	}

	public class SearchPageNavigationArg
	{
		public SearchPageMode Mode { get; set; }
		public string SearchContent { get; set; }
	}
}
